package com.nb.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.nb.entity.SysConfig;
import com.nb.entity.SysConfigHistory;
import com.nb.mapper.SysConfigHistoryMapper;
import com.nb.mapper.SysConfigMapper;
import com.nb.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.nb.mapper.SysConfigHistoryMapper;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {


    // 缓存所有配置
    @Cacheable(value = "sysConfigCache", key = "'allConfigs'")
    @Override
    public List<SysConfig> getAllConfigs() {
        return mapper.selectAll();
    }

    @Autowired
    private SysConfigHistoryMapper historyMapper;
    @Transactional
    @Override
    public boolean updateConfig(SysConfig config) {
        if (config == null || config.getConfigKey() == null) {
            return false;
        }

        // 查询旧值
        SysConfig oldConfig = mapper.selectOneByQuery(QueryWrapper.create()
                .where("config_key = ?", config.getConfigKey()));

        if (oldConfig == null) {
            return false;
        }

        // 更新配置
        config.setId(oldConfig.getId());
        int updated = mapper.update(config);

        // 刷新缓存
        refreshCache();

        return updated > 0;
    }

    @CacheEvict(value = "sysConfigCache", allEntries = true)
    @Override
    public void refreshCache() {
        // 清空缓存，下次访问时自动加载最新数据
    }
    @Override
    public List<SysConfig> getPublicConfigs() {
        // 构建查询条件：筛选is_public=1的配置
        QueryWrapper queryWrapper = QueryWrapper.create()
                .eq("is_public", 1)  // 等价于 WHERE is_public = 1
                .isNotNull("config_key");  // 排除config_key为空的记录

        // 直接通过BaseMapper的selectList方法查询，无需XML映射
        return mapper.selectListByQuery(queryWrapper);
    }

    @Override
    public List<SysConfigHistory> getHistoryByPage(
            Integer configId,  // 移除分页参数
            LocalDateTime startTime,
            LocalDateTime endTime) {
        // 直接查询全量历史记录
        return historyMapper.selectAllHistory(configId, startTime, endTime);
    }

}